<?php
error_reporting(E_ALL);

define("LIBS",dirname(__FILE__).DIRECTORY_SEPARATOR."libs".DIRECTORY_SEPARATOR);
define("HANDLERS",dirname(__FILE__).DIRECTORY_SEPARATOR."handlers".DIRECTORY_SEPARATOR);
define("SERVER_HOST",$_SERVER["HTTP_HOST"]);

if(is_int(strpos(PHP_OS,"WIN"))) {
	//@see apache bug https://issues.apache.org/bugzilla/show_bug.cgi?id=41441
    define("MAGIC_STR","index.php/");
}else{
    define("MAGIC_STR","");
}

require_once HANDLERS."blogspot.handler.php";
require_once HANDLERS."blogspotComment.handler.php";
require_once HANDLERS."proxypassReverse.handler.php";
require_once HANDLERS."mobileDevice.handler.php";

function run_handler($handler_name, $url, $base_path) {
	define("URL_BASE_PATH",$base_path);
	call_user_func($handler_name,$url);
}

function main(){

    $uri = $_SERVER["REQUEST_URI"];

	// 第一部分正则表达式
	// 第二部分要执行的函数
	// 第三部分页面内URLRewrite 的需附加的路径
	$commands_reg = "((![\w:,_\-&\$]*)*)";
    $special_urls_config = array(
        array("/^\/(\?)?".$commands_reg."\/?(https?\:\/\/.*)/","proxypass_reverse","$2"),
        array("/^\/(index\.php)\?".$commands_reg."\/?(https?\:\/\/.*)/","proxypass_reverse","$2"),
        array("/^\/(index\.php\/)?".$commands_reg."\/?(https?\:\/\/.*)/","proxypass_reverse","$2"),
        array("/^\/(index\.php\/)?\??kindle".$commands_reg."\/(.*)/","kindle_handler","kindle$2"),
        array("/^\/(index\.php\/)?\??iphone".$commands_reg."\/(.*)/","iphone_handler","iphone$2"),
        array("/^\/(index\.php\/)?\??ipad".$commands_reg."\/(.*)/","ipad_handler","ipad$2"),
        array("/^\/(index\.php\/)?\??comment\/(.*)/","blogspot_comment",""),
        array("/^\/(index\.php\/)?(.*)/","blogspot",""),
    );

    foreach( $special_urls_config as $config){
        $pattern = $config[0];
        $action = $config[1];
		$base_path = $config[2];
		$uri_dummy = substr($uri,0);
		$base_path = preg_replace($pattern,$base_path,$uri_dummy);
		if (!empty($base_path)) {
            $base_path .= "/";
		}
		preg_match($pattern,$uri,$matched);
        if($matched){
            run_handler($action,$matched[count($matched)-1],$base_path);
            exit();
        }
    }

	echo "pattern not found";
}

main();
